package com.yuki.weather.db;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.Toast;
import com.yuki.weather.data.City;
import com.yuki.weather.util.HttpUtils;
import com.yuki.weather.util.JsonUtils;

import java.util.List;

public class GenerateDatabaseTask extends AsyncTask<Void, Integer, Integer> {
    private Activity activity;
    private ProgressDialog progressDialog;
    private String baseUrl = "http://guolin.tech/api/china";
    private CityDatabase cityDatabase;

    public GenerateDatabaseTask(Activity activity, CityDatabase cityDatabase) {
        this.activity = activity;
        this.cityDatabase = cityDatabase;
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        progressDialog.dismiss();
        showToast(String.format("Insert %d data into database", integer));
    }

    private void showToast(String s) {
        Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
    }

    private void iniProgressDialog(int max) {
        progressDialog = new ProgressDialog(activity);
        progressDialog.setTitle("Generating database");
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Inserted data:");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(max);
        progressDialog.setProgress(0);
        progressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setProgress(values[0]);
        progressDialog.setMessage(String.format("Inserted data:%d", values[1]));
    }

    @Override
    protected Integer doInBackground(Void... params) {
        int count = 0;
        String ack = HttpUtils.getOkHttpBlock(baseUrl);
        final List<City> provinceList = JsonUtils.getCityListFromJson(ack, -1, 0);
        if (provinceList != null && provinceList.size() > 0) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    iniProgressDialog(provinceList.size());
                }
            });
            cityDatabase.clearDatabase();
            count = count + cityDatabase.insertList(provinceList);
            for (int i = 0; i < provinceList.size(); i++) {
                City province = provinceList.get(i);
            }
        }
        return count;
    }
}
